package com.ebb;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.kinvey.KCSClient;
import com.kinvey.KinveyUser;
import com.kinvey.util.KinveyCallback;
import com.kinvey.util.ScalarCallback;

public class EBBMemberActivity extends Activity implements OnClickListener {
	private EditText etNick;
	private Button btnModify;
	private String msgResponse;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.member);
		
		initLayout();
	}
	
	public void initLayout() {
		this.etNick = (EditText) findViewById(R.id.nick_value);

		this.btnModify = (Button) findViewById(R.id.modify_button);
		this.btnModify.setId(0x2001);
		this.btnModify.setOnClickListener(this);
	}
	
	/**
	 * Display a simple alert dialog with the given text and title.
	 * 
	 * @param context
	 *            Android context in which the dialog should be displayed
	 * @param title
	 *            Alert dialog title
	 * @param text
	 *            Alert dialog message
	 */
	protected static void showAlert(Context context, String title, String text) {
		Builder alertBuilder = new Builder(context);
		alertBuilder.setTitle(title);
		alertBuilder.setMessage(text);
		alertBuilder.create().show();
	}

	@Override
	public void onClick(View v) {
		KCSClient service = ((EBBKinveyApplication) getApplication()).getKinveyService();
		final KinveyUser currentUser = service.getCurrentUser();
		
		String nickValue = etNick.getText().toString();
		
		switch (v.getId()) {
		case 0x2001: // Save
			if (nickValue.length() > 0) {
				currentUser.setAttribute("nickname", etNick.getText().toString());
				currentUser.save(new ScalarCallback<Void>() {
					@Override
					public void onSuccess(Void e) {
						currentUser.loginWithUsername(currentUser.getUsername(), EBBVariable.getVal(), new KinveyCallback<Boolean>() {
							@Override
							public void onSuccess(Boolean e) {
								msgResponse = "Hello! " + currentUser.getAttribute("nickname").toString();
								Toast.makeText(getBaseContext(), msgResponse, Toast.LENGTH_LONG).show();
								Intent i = new Intent("com.ebb.EBBKinveyActivity2");
								startActivity(i);
							}
							
							@Override
							public void onFailure(Throwable e) {
								super.onFailure(e);
								e.printStackTrace();
							}
						});
					}
					
					@Override
					public void onFailure(Throwable e) {
						super.onFailure(e);
						e.printStackTrace();
					}
				});
			} else {
				showAlert(EBBMemberActivity.this, "EBB Modify", "Failure!");
			}
			break;
		}
	}
}